<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="所属园区" prop="schoolCode">
        <el-select v-model="formData.schoolCode" placeholder="请选择所属园区">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SCHOOL_CODE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!--  园区和班级应该联动选择  TODO  -->
      <el-form-item label="班级ID" prop="classId">
        <el-input v-model="formData.classId" placeholder="请输入班级ID" />
      </el-form-item>

      <el-form-item label="餐别" prop="mealType">
        <el-select v-model="formData.mealType" placeholder="请选择餐别">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SCHOOL_MEAL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="主食剩余量" prop="stapleFoodWaste">
        <el-input-number
          v-model="formData.stapleFoodWaste"
          :min="0"
          placeholder="请输入主食剩余量（kg）"
          clearable
          controls-position="right"
          class="!w-1/1"
        />
      </el-form-item>
      <el-form-item label="副食剩余量" prop="sideDishWaste">
        <el-input-number
          v-model="formData.sideDishWaste"
          :min="0"
          placeholder="请输入副食剩余量（kg）"
          clearable
          controls-position="right"
          class="!w-1/1"
        />
      </el-form-item>

      <el-form-item label="剩余餐原因" prop="wasteReason">
        <el-input v-model="formData.wasteReason" type="textarea" placeholder="请输入剩余餐原因" />
      </el-form-item>
      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="formData.recordDate"
          type="date"
          value-format="x"
          placeholder="选择记录日期"
        />
        <el-tooltip class="item" :content="'如果不填，默认为当天'" effect="light" placement="top">
          <Icon icon="ep:question-filled" class="ml-5px" />
        </el-tooltip>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { RecipeFoodWasteApi, RecipeFoodWaste } from '@/api/school/recipe/waste'

/** 厨余登记 表单 */
defineOptions({ name: 'RecipeFoodWasteForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  mealType: undefined,
  classId: undefined,
  schoolCode: undefined,
  stapleFoodWaste: undefined,
  sideDishWaste: undefined,
  wasteReason: undefined,
  recordDate: undefined,
  sort: undefined,
  status: 0
})
const formRules = reactive({
  schoolCode: [{ required: true, message: '园区不能为空', trigger: 'change' }],
  mealType: [{ required: true, message: '餐别不能为空', trigger: 'change' }],
  classId: [{ required: true, message: '班级ID不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  stapleFoodWaste: [{ required: true, message: '主食剩余量不能为空', trigger: 'blur' }],
  sideDishWaste: [{ required: true, message: '副食剩余量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RecipeFoodWasteApi.getRecipeFoodWaste(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RecipeFoodWaste
    if (formType.value === 'create') {
      await RecipeFoodWasteApi.createRecipeFoodWaste(data)
      message.success(t('common.createSuccess'))
    } else {
      await RecipeFoodWasteApi.updateRecipeFoodWaste(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mealType: undefined,
    classId: undefined,
    schoolCode: undefined,
    stapleFoodWaste: undefined,
    sideDishWaste: undefined,
    wasteReason: undefined,
    recordDate: undefined,
    sort: undefined,
    status: 0
  }
  formRef.value?.resetFields()
}
</script>
